package com.cyan.app.workflow.activity.WHM;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cyan.app.barcode.CaptureActivity;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.Invbat2LabBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.PullDownView;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.network.GetRequestParams;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 区域库位调拨-新增
 * Created by DXW on 2016-07-07.
 */
public class AreaDbNewActivity extends BaseActivity implements PullDownView.OnPullDownListener {
    public static final String TAG = "AreaDbNewActivity";
    private TextView mTextViewFixnr;
    private Button mButton;
    private RelativeLayout mRelativeLayout;
    //private MannoLzAdapter adapter;
    private ListView areaDbinfo_lv;
    private PullDownView mPullDownView;
    private ShowTipDialog showdialog = new ShowTipDialog();
    private List<Invbat2LabBean.Invbat2Bean> mInvbat2BeanList;
    private AreaDbNewAdapter adapter;
    private int selectedCount=0;
    private String fixnr;
    private boolean[] checks; //用于保存checkBox的选择状态
    private Double[] dbNums; //用于保存checkBox的选择状态
    private int pageCount = 10;
    private Boolean isPressMore = false;
    /** 是否有下一页 */
    private boolean nextPage = false;
    /** 请求第几页数据 */
    private int intPageNo = 1;
    private List<Invbat2LabBean.Invbat2Bean> mInvbat2BeanListShow = new ArrayList<Invbat2LabBean.Invbat2Bean>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.whm_area_db_new);
        initView();
        submit();
       /* fixnr = "15";
        mTextViewFixnr.setText(fixnr);
        AsyncLoader task = new AsyncLoader();
        task.execute("313", fixnr);*/
        startActivityForResult(new Intent(AreaDbNewActivity.this, CaptureActivity.class), 0x0001);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==0x0001&&resultCode==RESULT_OK){
            String result = "";
            if(data==null){
                return;
            }

            result = data.getStringExtra("result");
            fixnr = String.valueOf(result);
            if(!fixnr.contains("10010"))
            {
                AppUtils.showTip(AreaDbNewActivity.this, "请扫描现场库位条码。");
                return;
            }
            fixnr = fixnr.substring(9);
            mTextViewFixnr.setText(fixnr);
            AsyncLoader task = new AsyncLoader();
            task.execute("313", fixnr);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private void initView(){
        titleBar();

        mTextViewFixnr = (TextView) findViewById(R.id.top_search);
        /*
		 * 1.使用PullDownView 2.设置OnPullDownListener 3.从mPullDownView里面获取ListView
		 */
        mPullDownView = (PullDownView) findViewById(R.id.whm_area_db_new_lv);

        mPullDownView.setOnPullDownListener(this);

        areaDbinfo_lv = mPullDownView.getListView();
        // 隐藏并且禁用头部刷新
        mPullDownView.setHideHeader();
        // 隐藏 并禁用尾部
        //mPullDownView.setHideFooter();

    }
    private void titleBar() {
        EditText editText1 = (EditText) findViewById(R.id.top_search);
        Drawable drawable1 = getResources().getDrawable(R.drawable.search_icon2);
        drawable1.setBounds(0, 0, 40, 40);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
        editText1.setCompoundDrawables(drawable1, null, null, null);//只放左边
        editText1.setInputType(InputType.TYPE_NULL);
        editText1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(AreaDbNewActivity.this, CaptureActivity.class), 0x0001);
            }
        });

        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                finish();
            }
        });
        mButton = (Button)findViewById(R.id.top_title_refres_with_icon);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(AreaDbNewActivity.this, CaptureActivity.class), 0x0001);
            }
        });

        RelativeLayout mRelativeLayout =(RelativeLayout) findViewById(R.id.whm_area_db_new_foot);
        mRelativeLayout.setVisibility(View.VISIBLE);
    }
    //提交事件
    private void submit(){
        Button btnSub=(Button)findViewById(R.id.whm_area_db_new_btn_sub);
        btnSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedCount <= 0) {
                    AppUtils.showTip(AreaDbNewActivity.this, "请选择调拨品号。");
                    return;
                }
                List<Invbat2LabBean.Invbat2Bean> resultList = new ArrayList<Invbat2LabBean.Invbat2Bean>();
                Invbat2LabBean result = new Invbat2LabBean();
                for (int i = 0; i < mInvbat2BeanListShow.size(); i++) {
                    if (!checks[i]) {
                        continue;
                    }
                    if (dbNums[i] > mInvbat2BeanListShow.get(i).getOnhand1()) {
                        AppUtils.showTip(AreaDbNewActivity.this,mInvbat2BeanListShow.get(i).getItnbr()+ "调拨数量不能大于库存数量");
                        return;
                    }
                    mInvbat2BeanListShow.get(i).setOnhand1(dbNums[i]);
                    resultList.add(mInvbat2BeanListShow.get(i));
                }
                result.setResult(resultList);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("area_db_new",result);
                intent.putExtras(bundle);
                setResult(RESULT_OK,intent);
                finish();
            }
        });

    }
    public class AsyncLoader extends AsyncTask<String,Integer,String>
    {
        @Override
        protected void onPreExecute() {
            showdialog.showDialog(AreaDbNewActivity.this);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            try{
                JSONObject param = new JSONObject();
                param.put("Fixnr", params[1]);
                result= GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, params[0], param.toString(), getApplicationContext());
            }catch (Exception e){
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null||s.isEmpty()) {
                showdialog.closeDialog();
                return;
            }
            Invbat2LabBean commonBean = new Gson().fromJson(s, Invbat2LabBean.class);
            if (commonBean.getCode() < 1) {
                AppUtils.showTip(AreaDbNewActivity.this, commonBean.getMsg());
            } else {
                mInvbat2BeanList = commonBean.getResult();
                /*adapter = new AreaDbNewAdapter(AreaDbNewActivity.this);
                areaDbinfo_lv.setAdapter(adapter);*/
                showList();
            }
            showdialog.closeDialog();
        }
    }

    private void  showList(){
        // 获取更多数据之外的请求，如首次请求数据，
        if (!isPressMore) {
            getData(intPageNo);
            adapter = new AreaDbNewAdapter(AreaDbNewActivity.this);
            areaDbinfo_lv.setAdapter(adapter);
        }else {
            // 获取更多数据
            getData(intPageNo);
            adapter.notifyDataSetChanged();
        }
        // 判断是否有下一页
        if (mInvbat2BeanList.size() > mInvbat2BeanListShow.size()) {
            // 显示并启用自动获取更多
            mPullDownView.setShowFooter();
            // 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
            mPullDownView.enableAutoFetchMore(true, 1);
        } else {
            // 隐藏 并禁用尾部
            mPullDownView.setHideFooter();
            // 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
            mPullDownView.enableAutoFetchMore(false, 1);
        }
        // 告诉它获取更多完毕 这个事线程安全的 可看源代码
        mPullDownView.notifyDidMore();

        isPressMore = false;
    }
    private void getData(int PageNo){
        if(mInvbat2BeanList==null) return;
        int count = (intPageNo*pageCount)> mInvbat2BeanList.size()?mInvbat2BeanList.size():intPageNo*pageCount;
        for(int i = (intPageNo-1)* pageCount;i< count;i++){
            mInvbat2BeanListShow.add(mInvbat2BeanList.get(i));
        }
    }
    /**
     * listview刷新
     */
    public void onRefresh() {

    }
    /**
     * listview更多
     */
    public void onMore() {
        isPressMore = true;
        // 发送更多请求
        intPageNo++;
        showList();
    }

    public  class  AreaDbNewAdapter extends BaseAdapter{
        private LayoutInflater inflater = null;
        public AreaDbNewAdapter(Context context) {
            inflater=LayoutInflater.from(context);
            checks =  new boolean[mInvbat2BeanList.size()];
            dbNums =  new Double[mInvbat2BeanList.size()];
            for (int i=0;i< mInvbat2BeanList.size();i++){
                dbNums[i]=mInvbat2BeanList.get(i).getOnhand1();
            }
        }

        @Override
        public int getCount() {
            return mInvbat2BeanListShow.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView( final int position, View convertView, ViewGroup parent) {
           ViewHolder holder =null;
//            if(convertView==null) {
                holder = new ViewHolder();
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.gravity = Gravity.CENTER_VERTICAL;
                convertView = inflater.inflate(R.layout.whm_area_db_new_list, null);
                holder.itnbr_bat_itnbr = (TextView) convertView.findViewById(R.id.whm_area_db_new_list_itnbr);
                holder.itnbr_bat_itnbr.setText(mInvbat2BeanListShow.get(position).getItnbr());

                holder.itnbr_bat_itdsc = (TextView) convertView.findViewById(R.id.whm_area_db_new_list_itdsc);
                holder.itnbr_bat_itdsc.setText(mInvbat2BeanListShow.get(position).getItdsc());

                holder.itnbr_bat_onhand1 = (TextView) convertView.findViewById(R.id.whm_area_db_new_list_onhand1);
                holder.itnbr_bat_onhand1.setText(mInvbat2BeanListShow.get(position).getOnhand1().toString());

                holder.itnbr_bat_onhand2 = (TextView) convertView.findViewById(R.id.whm_area_db_new_list_onhand2);
                //holder.itnbr_bat_onhand2.setText(mInvbat2BeanListShow.get(position).getOnhand1().toString());
                holder.itnbr_bat_onhand2.setText(dbNums[position].toString());

                holder.itnbr_bat_selected = (CheckBox) convertView.findViewById(R.id.whm_area_db_new_list_selected);
                convertView.setTag(holder);

//              dbNums[position]=mInvbat2BeanListShow.get(position).getOnhand1();
            holder.itnbr_bat_onhand2.addTextChangedListener(new TextWatcher() {
                Double num = 0.00;
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }
                @Override
                public void afterTextChanged(Editable s) {
                    if (!s.toString().isEmpty()) {
                            num = Double.parseDouble(s.toString());
                            dbNums[position]=num;
                    }
                }
            });
         /*   }
            else {
                holder = (ViewHolder)convertView.getTag();
            }*/
            final int pos = position;
            holder.itnbr_bat_selected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        selectedCount++;
                    } else {
                        selectedCount--;
                    }
                    checks[pos] = isChecked;
                }
            });
            holder.itnbr_bat_selected.setChecked(checks[position]);

            return convertView;
        }
        class ViewHolder {
            CheckBox itnbr_bat_selected;
            TextView itnbr_bat_itnbr;
            TextView itnbr_bat_itdsc;
            TextView itnbr_bat_onhand1;
            TextView itnbr_bat_onhand2;
        }
    }
}
